<%@ page pageEncoding="UTF-8"%>
<%@ include file="/common/validate.jsp"%>
<%!
		// 准备问卷
	Message survey(Integer hospital, Integer surveyUid) {
		Message msg = new Message();
		List<Survey> list = QBuilder.db("basedb").queryHql("from Survey where id=" + surveyUid);
		Map<String, Object> surveyMap = new HashMap<String, Object>();
		List<Map<String, Object>> quests = new ArrayList<Map<String, Object>>(); // 问题列表
		if (list.size() == 0) { // 问卷不存在
			msg.setErrcode(30041);
			msg.setErrmsg("问卷不存在");
			return msg;
		}
		// 问卷标题和id
		Survey survey = list.get(0);
		String title = survey.getTitle();
		Integer id = survey.getId();
		surveyMap.put("title", title);
		surveyMap.put("id", id);

		// 查询该问卷中所有问题
		List<SurveyQuestion> questList = QBuilder.db("basedb").queryHql("from SurveyQuestion where status=1 and surveyId="+id + "order by showOrder asc");
		// 所有问题id
		String questIds = "-1,";
		for (int i = 0; i < questList.size(); i++) {
			SurveyQuestion quest = questList.get(i);
			Integer questId = quest.getId();
			questIds += questId + ",";
		}
		questIds = questIds.substring(0, questIds.length() - 1);

		// 根据问题id查出问题选项
		Map<Integer, List<Map<String, Object>>> questIdMap = new HashMap<Integer, List<Map<String, Object>>>(); // 问题和问题选项集合
		List<SurveyOptions> optionList = QBuilder.db("basedb").queryHql("from SurveyOptions where status=1 and questId in(" + questIds + ") order by showOrder asc");
		for (int i = 0; i < optionList.size(); i++) {
			SurveyOptions option = optionList.get(i);
			String content = option.getContent();
			Integer optionId = option.getId();
			Integer questId = option.getQuestId();
			List<Map<String, Object>> options = questIdMap.get(questId);
			if (null == options) {
				options = new ArrayList<Map<String, Object>>();
			}
			Map<String, Object> anOption = new HashMap<String, Object>();
			anOption.put("content", content);
			anOption.put("option_id", optionId);
			anOption.put("score", option.getScore());
			options.add(anOption);
			questIdMap.put(questId, options);
		}

		// 问题选项加到对应的问题中
		for (int i = 0; i < questList.size(); i++) {
			SurveyQuestion quest = questList.get(i);
			String questTitle = quest.getTitle();
			Integer questId = quest.getId();
			Integer type = quest.getType();
			Map<String, Object> aQuest = new HashMap<String, Object>();
			aQuest.put("title", questTitle);
			aQuest.put("quest_id", questId);
			aQuest.put("type", type);
			aQuest.put("options", questIdMap.get(questId));
			quests.add(aQuest);
		}
		surveyMap.put("quests", quests);
		msg.put("data", surveyMap);
		return msg;
	}
%>
<%
	Integer surveyId = input.getInt("survey_id", -1);
	Tools.encryptPrint(out, survey(hospital, surveyId));
%>